﻿using RpcHelper;
using RpcHelper.Config;

namespace SqlSugarHelper.Config
{
    internal class SugarConfig : ISugarConfig
    {
        private static Dictionary<string, LogConfig> _defSet = new Dictionary<string, LogConfig>
        {
            {"Error", new LogConfig("SqlSugar", LogGrade.ERROR)},
            {"Log", new LogConfig("SqlSugar", LogGrade.DEBUG)}
        };
        private Dictionary<string, LogConfig> _LogConfig = new Dictionary<string, LogConfig>();
        public SugarConfig(IConfigCollect config)
        {
            this.IsLocalLog = config.GetValue<bool>("SqlSugar:IsLocalLog", false);
            this._LogConfig = config.GetValue("SqlSugar:Log", _defSet);
            config.RefreshEvent += this.Config_RefreshEvent;
        }

        private void Config_RefreshEvent(IConfigCollect config, string name)
        {
            if (name == "SqlSugar:IsLocalLog")
            {
                this.IsLocalLog = config.GetValue<bool>("SqlSugar:IsLocalLog", false);
            }
            else if (name == "SqlSugar:Log" || name.StartsWith("SqlSugar:Log:"))
            {
                this._LogConfig = config.GetValue("SqlSugar:Log", _defSet);
            }
        }

        /// <summary>
        /// 是否本地日志
        /// </summary>
        public bool IsLocalLog
        {
            get;
            private set;
        } = false;

        public bool CheckIsRecord(string key, out LogConfig logSet)
        {
            if (_LogConfig.TryGetValue(key, out logSet))
            {
                return LogSystem.CheckIsRecord(logSet.LogGrade);
            }
            return false;
        }

        public bool CheckIsRecord(string key, ErrorException e, out LogConfig logSet)
        {
            if (_LogConfig.TryGetValue(key, out logSet))
            {
                return LogSystem.CheckIsRecord(e);
            }
            return false;
        }
      
    }
}
